<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="168px">
      <el-form-item label="供应商名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入供应商名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省份" prop="state">
        <el-input
          v-model="queryParams.state"
          placeholder="请输入省份"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入城市"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区域" prop="address2">
        <el-input
          v-model="queryParams.address2"
          placeholder="请输区域"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商详细地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入供应商详细地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="传真" prop="fax">
        <el-input
          v-model="queryParams.fax"
          placeholder="请输入传真"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="queryParams.notes"
          placeholder="请输入备注"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮政编码" prop="zip">
        <el-input
          v-model="queryParams.zip"
          placeholder="请输入邮政编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="官网链接" prop="url">
        <el-input
          v-model="queryParams.url"
          placeholder="请输入官网链接"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['vadmin/basic:suppliers:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['vadmin/basic:suppliers:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['vadmin/basic:suppliers:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['admin:assets:assets:export']"
          type="primary"
          plain
          icon="el-icon-position"
          size="mini"
          :loading="exportLoading"
          @click="handleInput"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['vadmin/basic:suppliers:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="suppliersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column width="155" label="供应商名称" align="center" prop="name"  sortable />
      <el-table-column width="155" label="省份" align="center" prop="state"  sortable />
      <el-table-column width="155" label="城市" align="center" prop="city"  sortable />
      <el-table-column width="155" label="区域" align="center" prop="address2"  sortable />
      <el-table-column width="155" label="供应商地址" align="center" prop="address"  sortable />
      <el-table-column width="155" label="手机号" align="center" prop="phone"  sortable />
      <el-table-column width="155" label="传真" align="center" prop="fax"  sortable />
      <el-table-column width="200" label="邮箱" align="center" prop="email"  sortable />
      <el-table-column width="155" label="联系人" align="center" prop="contact"  sortable />
      <el-table-column width="155" label="备注" align="center" prop="notes"  sortable />
      <el-table-column width="155" label="邮政编码" align="center" prop="zip"  sortable />
      <el-table-column width="155" label="官网链接" align="center" prop="url"  sortable />
      <el-table-column width="155" label="图片" align="center" prop="image" >
        <div slot-scope="scope">
          <img v-if="scope.row.image" :src="scope.row.image" style="width: 50px;height: 50px" />
        </div>>
      </el-table-column>
      <!--      <el-table-column label="创建者" align="center" prop="creator_id" />-->
      <el-table-column label="操作" fixed="right" width="155" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['vadmin/basic:suppliers:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['vadmin/basic:suppliers:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改供应商对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="选择地址" >
          <el-cascader
            v-model="selectedOptions"
            size="small"
            :options="options"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="供应商详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入供应商详细地址" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="传真" prop="fax">
          <el-input v-model="form.fax" placeholder="请输入传真" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="邮政编码" prop="zip">
          <el-input v-model="form.zip" placeholder="请输入邮政编码" />
        </el-form-item>
        <el-form-item label="官网链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入官网链接" />
        </el-form-item>
        <el-form-item label="图片上传">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload"
            size="mini"
            @click="imageUpload"
          >图片上传
          </el-button>
          <img v-if="form.image" :src="form.image" class="avatar">
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 图片上传 -->
    <el-dialog :title="title1" :visible.sync="open1" width="400px" append-to-body @close="open1 = false">
      <FileUpload ref="saveFile" :file-type="['ALL']" @input="fileGet" />
    </el-dialog>
    <InputFile ref="inputfile" @inputFile="inputFile"></InputFile>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import {
  listSuppliers,
  getSuppliers,
  delSuppliers,
  addSuppliers,
  updateSuppliers,
  exportSuppliers,
  importsSuppliers
} from "@/api/vadmin/basic/suppliers";
import { regionData, codeToText } from "element-china-area-data";
import FileUpload from "@/components/FileUpload/index";
import InputFile from "@/views/components/InputFile";

export default {
  name: "Suppliers",
  components: { InputFile, FileUpload },
  data() {
    return {
      title1: "",
      open1: false,
      options: regionData,
      selectedOptions: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商表格数据
      suppliersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        description: null,
        modifier: null,
        dept_belong_id: null,
        update_datetime: null,
        create_datetime: null,
        name: null,
        address: null,
        address2: null,
        city: null,
        state: null,
        country: null,
        phone: null,
        fax: null,
        email: null,
        contact: null,
        notes: null,
        deleted_datetime: null,
        zip: null,
        url: null,
        image: null,
        creator_id: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleInput() {
      this.$refs.inputfile.open();
    },
    inputFile(val) {
      // 是否更新已经存在的用户数据
      importsSuppliers(val).then(response => {
        this.$alert("导入成功！", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      });
    },
    fileGet(file) {
      this.open1 = false;
      this.$refs.saveFile.fileList = [];
      this.form.image = file;
    },
    imageUpload() {
      this.open1 = true;
      this.title1 = "图片上传";
    },
    handleChange(value) {
      this.getCodeToText(null, value);
    },
    getCodeToText(codeStr, codeArray) {
      if (codeStr === null && codeArray === null) {
        return null;
      } else if (codeArray === null) {
        codeArray = codeStr.split(",");
      }
      let area = "";
      switch (codeArray.length) {
          case 1:
            area += codeToText[codeArray[0]];
            this.form.state = codeToText[codeArray[0]];
            break;
          case 2:
            area += codeToText[codeArray[0]] + codeToText[codeArray[1]];
            this.form.state = codeToText[codeArray[0]];
            this.form.city = codeToText[codeArray[1]];
            break;
          case 3:
            area += codeToText[codeArray[0]] + codeToText[codeArray[1]] + codeToText[codeArray[2]];
            this.form.state = codeToText[codeArray[0]];
            this.form.city = codeToText[codeArray[1]];
            this.form.address2 = codeToText[codeArray[2]];
            break;
          default:
            break;
      }
      return area;
    },
    textToCode(region) {
      for (const province of this.options) {
        if (province.label === region) {
          return province.value;
        }
        if (province.children) {
          for (const city of province.children) {
            if (city.label === region) {
              return city.value;
            }
            if (city.children) {
              for (const area of city.children) {
                if (area.label === region) {
                  return area.value;
                }
              }
            }
          }
        }
      }
      return "";
    },
    /** 查询供应商列表 */
    getList() {
      this.loading = true;
      listSuppliers(this.queryParams).then(response => {
        this.suppliersList = response.data.results;
        this.total = response.data.count;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        description: null,
        modifier: null,
        dept_belong_id: null,
        update_datetime: null,
        create_datetime: null,
        name: null,
        address: null,
        address2: null,
        city: null,
        state: null,
        country: null,
        phone: null,
        fax: null,
        email: null,
        contact: null,
        notes: null,
        deleted_datetime: null,
        zip: null,
        url: null,
        image: null,
        creator_id: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSuppliers(id).then(response => {
        this.form = response.data;
        let province = ""; let city = ""; let district = "";
        if (this.form.state) {
          province = this.textToCode(this.form.state);
        }
        if (this.form.city) {
          city = this.textToCode(this.form.city);
        }
        if (this.form.address2) {
          district = this.textToCode(this.form.address2);
        }
        this.selectedOptions = [province, city, district];
        this.open = true;
        this.title = "修改供应商";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSuppliers(this.form).then(response => {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.open = false;
              this.getList();
            });
          } else {
            addSuppliers(this.form).then(response => {
              this.$message({
                message: "新增成功",
                type: "success"
              });
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delSuppliers(ids).then(res => {
          this.getList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportSuppliers(queryParams);
      }).then(response => {
        this.download(response.data.file_url, response.data.name);
      });
    }
  }
};
</script>
<style>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  margin-top: 15px;
}
</style>
